// 公共组件
import { dirListApi } from "@/api/imgStore";
import { useVModels, useVModel } from "@vueuse/core";
import { ES } from "@/api/esSearch";
import {
    Input,
    Select,
    Space,
    Button,
    message,
    TypographyText,
    Modal,
    Textarea,
    CheckboxGroup,
    Divider,
    SelectOption,
    Row,
    Col,
} from "ant-design-vue";
import { useCommonStaticOptions, useCommonAsyncOptions } from "@/hooks/useEsArticleCommon";
import type { OtherSearchItem } from "@/hooks/useEsArticleCommon";
import { getEsArtCountApi, getEsIndexsApi, getDomainSelectInfoApi } from "@/api/esArticle";
import type { VNode } from "vue";
type DirectoryItemType = ResponseType.MethodGet.ImgStoreListApi["data"][0];
type ImgDirectorySelectProps = {
    tags: Array<string>;
    dir: string;
    searchBody: Record<string, any>;
};
// 图片目录选择组件
export const ImgDirectorySelect = defineComponent({
    props: ["dir", "tags", "searchBody"],
    emits: ["update:dir", "update:tags", "update:searchBody"],
    setup(props: ImgDirectorySelectProps, { emit }) {
        const { dir, tags, searchBody } = useVModels(props, emit);
        const directoryOptions = ref<SelectOption>([]);
        const { filterOption } = useCommonStaticOptions();
        onMounted(() => {
            dirListApi({ page_size: 1000 }, "get").then((res) => {
                directoryOptions.value = res.data.data.map(({ tags, ...item }: DirectoryItemType) => ({
                    label: item.description,
                    value: item.dirname,
                    tags
                }));
            });
        });
        const tagOption = ref<SelectOption>([]);
        watch(dir, () => {
            const item = directoryOptions.value.find((item) => item.value === dir.value) as SelectOptionItem;
            // @ts-ignore
            tagOption.value = (item.tags as string).split(",").map((v) => ({ label: v, value: v }));
        });
        const es = new ES("90"); // es实例
        const total = ref(0);
        const isBreak = ref(true)
        const serachFun = () => {
            if (!dir.value) {
                return message.error("请选择!");
            }
            // 初始化查询条件
            const body: Record<string, any> = {
                query: {
                    bool: {
                        must: [
                            {
                                term: {
                                    "dirname.keyword": {
                                        value: dir.value
                                    }
                                }
                            }
                        ]
                    }
                }
            };
            if (tags.value.length) {
                body["query"]["bool"]["must"].push({
                    terms: {
                        "tags.keyword": tags.value
                    }
                });
            }
            // -1 随机
            if (pubnum.value !== -1) {
                body["query"]["bool"]["must"].push({
                    range: {
                        usenum: {
                            lte: pubnum.value
                        }
                    }
                });
            }
            es.count("img_system", body).then((res) => {
                total.value = res.data.data["count"];
                searchBody.value = body;
            });
        };
        const pubnum = ref(-1);
        return () => (
            <Space style={{ margin: "10px 0" }}>
                选择目录
                <Select
                    show-search
                    filter-option={filterOption}
                    style="width:150px"
                    options={directoryOptions.value}
                    v-model:value={dir.value}
                ></Select>
                选择tags
                <Select
                    show-search
                    filter-option={filterOption}
                    style="width:150px"
                    mode="multiple"
                    options={tagOption.value}
                    v-model:value={tags.value}
                ></Select>
                使用数
                <Input v-model:value={pubnum.value} style="width:100px"></Input>
                <Button type="link" onClick={serachFun}>
                    搜索
                </Button>
                <TypographyText code type="success">
                    总数:{total.value}
                </TypographyText>
            </Space>
        );
    }
});

// select
export const SelectComponent = defineComponent({
    props: ["value", "options", "title"],
    emits: ["update:value"],
    inheritAttrs: false,
    setup(props: { value: string; options: SelectOption; title: string }, { emit }) {
        const value = useVModel(props, "value", emit);
        const { filterOption } = useCommonStaticOptions();
        const attrs = useAttrs();
        return () => (
            <Space>
                <span>{props.title}</span>
                <Select
                    {...attrs}
                    v-model:value={value.value}
                    options={props.options}
                    filterOption={filterOption}
                    showSearch
                ></Select>
            </Space>
        );
    }
});

// Input
export const InputComponent = defineComponent({
    props: ["value", "title", "width"],
    emits: ["update:value"],
    inheritAttrs: false,
    setup(props: { value: string; title: string; width: number }, { emit }) {
        const value = useVModel(props, "value", emit);
        const attrs = useAttrs();
        return () => (
            <Space>
                <span>{props.title}</span>
                <Input {...attrs} v-model:value={value.value} style={{ width: props.width + "px" }}></Input>
            </Space>
        );
    }
});

type EsSearchComponentProps = {
    artWycOptions: SelectOption;
    artWycValue: string;
    esHostValue: string;
    esIndexValue: string;
    esSearch: PostPublishRuleParams["es_search"];
    type: "update" | "add";
    website: string;
};

type EsConditionSearchComponent = {
    visible: boolean;
    checkboxs: Array<string>;
    newSearchOptions: Array<OtherSearchItem>;
    sourceSearchOptions: Array<OtherSearchItem>;
};
// 搜索条件组件
export const EsConditionSearchComponent = defineComponent({
    props: ["visible", "checkboxs", "newSearchOptions", "sourceSearchOptions"],
    emits: ["update:visible", "update:checkboxs", "update:newSearchOptions"],
    setup(props: EsConditionSearchComponent, { emit }) {
        const { esSearchFieldOptions } = useCommonStaticOptions();
        // 对话框确定按钮
        const modalOk = () => {
            message.success("保存成功!");
            visible.value = false;
        };
        // eslint-disable-next-line vue/no-setup-props-destructure
        const sourceSearchOptions = props.sourceSearchOptions;
        // 搜索条件
        const { visible, checkboxs, newSearchOptions } = useVModels(props, emit);
        // checkBoxOptions 根据选择 渲染对应的输入框
        const checkboxGroupOptions = computed(() =>
            sourceSearchOptions.filter((item) => item.type === 1).map((item) => ({ value: item.key, label: item.title }))
        );
        watch(checkboxs, (newV) => {
            newSearchOptions.value = sourceSearchOptions.filter((item) => newV.includes(item.key));
            // 每次发生变化 将未选中的清空值掉
            sourceSearchOptions.forEach((item) => {
                if (!newV.includes(item.key)) {
                    item["value"] = "";
                }
            });
        });
        return () => (
            <Modal v-model:open={visible.value} title="其他搜索条件" style="width:600px" onOk={modalOk}>
                <Space>
                    <CheckboxGroup v-model:value={checkboxs.value} name="checkboxgroup" options={checkboxGroupOptions.value} />
                </Space>
                <Divider />
                <Space direction="vertical" size={3} style="width: 100%">
                    {newSearchOptions.value.map((item) => {
                        return (
                            <>
                                <div style="display: flex; width: 100%" key={item.key} v-show={item.type === 1}>
                                    <span style="width: 100px; display: block; line-height: 32px">{item.title}</span>
                                    <Textarea
                                        style="flex: 1; height: 32px;margin-right:5px"
                                        v-model:value={item.value}
                                        placeholder="输入多个|隔开"
                                        row={5}
                                    ></Textarea>
                                    <Select
                                        options={esSearchFieldOptions}
                                        v-model:value={item.selectValue}
                                        style="width: 140px"
                                        show-search
                                    ></Select>
                                </div>
                            </>
                        );
                    })}
                </Space>
            </Modal>
        );
    }
});

type PublishRuleOrArtSelectOptions = {
    createId: number | string;
    artWyc: string;
    ruleType: number | string;
    publishType: number | string;
    customIdentifier: string;
};
// selectOptions
export const PublishRuleOrArtSelectOptions = defineComponent({
    props: ["artWyc", "ruleType", "publishType", "customIdentifier", "createId"],
    emits: ["update:artWyc", "update:ruleType", "update:publishType", "update:customIdentifier", "update:createId"],
    setup(props: PublishRuleOrArtSelectOptions, { emit }) {
        const { createId, artWyc, ruleType, publishType, customIdentifier } = useVModels(props, emit);
        const { filterOption } = useCommonStaticOptions();
        const { customIdentifierOptions, artWycOptions, userOptions, ruleOptions, publishTypeOptions } =
            useCommonAsyncOptions("get");
        const selectDatas = computed(() => [
            {
                value: createId,
                label: "创建者",
                options: userOptions,
                style: { width: "120px" }
            },
            {
                value: artWyc,
                label: "伪原创类型",
                options: artWycOptions,
                style: { width: "140px" }
            },
            {
                value: ruleType,
                label: "规则类型",
                options: ruleOptions,
                style: { width: "130px" }
            },
            {
                value: publishType,
                label: "发布类型",
                options: publishTypeOptions,
                style: { width: "200px" }
            },
            {
                value: customIdentifier,
                label: "自定义标识符",
                options: customIdentifierOptions,
                style: { width: "120px" }
            }
        ]);
        return () => (
            <>
                <Space>
                    {selectDatas.value.map((item) => {
                        return (
                            <>
                                <span>{item.label}</span>
                                <Select
                                    options={item.options.value}
                                    showSearch={true}
                                    filterOption={filterOption}
                                    v-model:value={item.value.value}
                                    style={item.style}
                                ></Select>
                            </>
                        );
                    })}
                </Space>
            </>
        );
    }
});

export const DomainInfoSelectOptions = defineComponent({
    props: ["data"],
    emits: ["update:data"],
    setup(props: { data: DomainInfoSelectFields }, { emit }) {
        const { filterOption } = useCommonStaticOptions();
        const { data: selectFieldData } = useVModels(props, emit);
        const domainInfoSelectData = ref<DomainInfoSelectData>([]);
        const requiredFields = [
            "web_user",
            "link_user",
            "content_user",
            "website_type",
            "program_type",
            "adapt_type",
            "domain_account",
            "dns_account",
            "shipei_type"
        ]
        onMounted(() => {
            getDomainSelectInfoApi().then((res) => {
                if (res.data.code === 200) {
                    domainInfoSelectData.value = res.data.data.map((item: any) => {
                        item["data"].unshift({ id: -1, name: "请选择" });
                        item["selectValue"] = toRef(selectFieldData.value, item.fileds);
                        return item;
                    });
                }
            });
        });
        const multipleChoiceFields = ["multiple_choice_field1","multiple_choice_field2","multiple_choice_field3","ad_type2","kdy_member","website_group_type"]
        const slots = useSlots();
        const targetKeywordIndexVnode = ref<Array<VNode>>();
        onMounted(() => {
            nextTick(() => {
                setTimeout(() => {
                    if (slots.target_keyword_index) {
                        targetKeywordIndexVnode.value = slots.target_keyword_index();
                    }
                }, 1000);
            });
        });
        return () => (
            <Row align="middle" gutter={[10, 6]}>
                {domainInfoSelectData.value.map((item) => {
                    return (
                        <Col span={4} style="display:flex;align-items:center">
                            <div style="width:30%">
                                {requiredFields.includes(item.fileds) ? ( <i style="color:red;font-weight:700">* </i>) : undefined}
                                {item.name}
                            </div>
                            <div style="width:70%">
                            {
                                multipleChoiceFields.includes(item.fileds) ? 
                            
                                <Select
                                    v-model:value={item.selectValue}
                                    style="width:100%"
                                    filterOption={filterOption}
                                    showSearch
                                    mode='multiple'
                                >
                                    {item.data.map((item2) => {
                                        return <SelectOption value={item2.id}>{item2.name}</SelectOption>;
                                    })}
                                </Select> :
                                 
                                 <Select
                                    v-model:value={item.selectValue}
                                    style="width:100%"
                                    filterOption={filterOption}
                                    showSearch
                                >
                                    {item.data.map((item2) => {
                                        return <SelectOption value={item2.id}>{item2.name}</SelectOption>;
                                    })}
                                </Select>
                            }
                                
                            </div>
                        </Col>
                    );
                })}
                <div style="margin-left:5px">{targetKeywordIndexVnode.value}</div>
            </Row>
        );
    }
});
